$(document).ready(function() {

    var loadingImg = $("#load_img");
    loadingImg.hide();
    
    var wordsHeader =  $("div#words_header");
    wordsHeader.hide();
    
    var numWords = $("#num_words");
    var lange = $("#lang");
    var prntBut = $("#btn_print");
    var showBut = $("#btn_show");
    var tableResult =  $("div#tableResult");
    var showForm =  $("form#show_form");
    var tip = $("div#tip");
    var print_t = $("#print_t");
    var cell = $(".outCell");
     
    var menu = $("div#menu");
    var header_line = $("div#header");
    var main = $("div.main");
    var offset = $("#offset");
    var footer = $("div#footer"); 
    var container = $("div#container");
    
    /*'SUBMIT' EVENT TO SHOW WORDS*/
    showForm.submit(function() {
        var used_words = get_used_words(tableResult.html());
        var res = "";
        
        loadingImg.show();
        $.post(path_ajax + "/user/showWords.php", {
            num_words: numWords.val(),
            lang: lange.val(),
            complexity: $('input:radio[name=complexity]:checked').val(),
            all_words: used_words
        },
        function(result) { //RESULT - STRING WITH WORDS SEPARATED BY NEW LINE
            loadingImg.hide();
            
            tip.html("нажми на слово, чтобы заменить");
            
            if(result != "no words"){
                result = $.trim(result);
                arr_word = result.split("\n");
                
                for(var i = 0; i < arr_word.length; i++){
                    if(arr_word[i] != ""){
                        res = res + "<div class=\"outCell\" id=\"fantd" + i + "\">" + arr_word[i] + "<br></div>\n";
                    }
                }
                tableResult.html(res);
                wordsHeader.show();
                setHeight(header_line, offset, main,  footer, offsetMain,container);  
            }
            else{
                alert("Показаны все слова имеющиеся в базе.");
            }
        });
        
        return false;
    });
    
    
    /*CLICK ON 'PRINT' BUTTON*/
    prntBut.click(function() {
        var used_words = get_used_words(tableResult.html());
        var t = "";
        var wordsInBase = true;
        
        $.ajaxSetup({async:false});//WAS NOT PRINTING CORRECTLY WITHOUT IT
        
        //IF PRINT PRESSED BEFORE "SHOW"
        if(tableResult.html() === ""){
            loadingImg.show();
            $.post(path_ajax + "/user/showWords.php", {
                num_words: numWords.val(),
                lang: lange.val(),
                complexity: $('input:radio[name=complexity]:checked').val(),
                all_words: used_words
            },
            function(result) {//RESULT - WORDS DILIMITED BY NEW LINE
                loadingImg.hide();
                used_words = result;
                
                if(result == "no words"){
                    wordsInBase = false;
                    alert("В базе нет слов для данных параметров.");
                }
           });
        }
        
        if(wordsInBase){
            print_t.html(make_table(used_words));
            print();
            $(window).scrollTop(0);
        }
        
        $.ajaxSetup({async:true});
        
        return false;
    });
    
    /*IF MOUSE IS ABOVE THE CELL*/
    cell.live("mouseenter", function(){
        $(this).css('border', border_on);
        $(this).css('color', color_cell_on);
        $(this).css('font-size', size_cell_on);
        $(this).css('font-weight','bold');
    });
    
    /*IF MOUSE LEFT THE CELL*/
    cell.live("mouseleave",function(){
        $(this).css('border', border_out);
        $(this).css('color', color_cell_on);
        $(this).css('font-size', size_cell);
        $(this).css('font-weight','normal');
        
    });
    
    /*CLICKING EVENT ON EACH WORD*/
    cell.live("click", function(){
    
        RemoveSelection();
         
        var id_clicked = this.id;
        var used_words = get_used_words(tableResult.html());
        var curr = $("div#" + id_clicked).html();
        loadingImg.show();
        $.post(path_ajax + "/user/changeWord.php", {
            complexity: $('input:radio[name=complexity]:checked').val(),
            current_word: curr, 
            all_words: used_words 
        },
        function(result) {
            loadingImg.hide();
            if((curr.indexOf(result,0)) == -1){ 
                $("div#" + id_clicked).fadeIn("slow").html(result + "<br>");
            }//IF NO MORE WORDS IN DATABASE, THEN DO NOTHING
        });
        
        return false;
    });
    
    /*CHANGE NUMBER OF WORDS IN COMBOBOX EVENT, CLEAR ALL WORDS*/
    numWords.change(function() {
        tableResult.html("");
        wordsHeader.hide();
        setHeight(header_line,  offset, main,  footer, offsetMain,container);
    });
    
    /*CHANGE EVENT FOR RADIO BUTTON, CLEAR ALL WORDS*/
    $('input:radio[name=complexity]').bind("change", function () {
        tableResult.html("");
        wordsHeader.hide();
        setHeight(header_line,  offset, main,  footer, offsetMain,container);
    }); 
    
    /*CHANGE LANGUAGE EVENT, CLEAR ALL WORDS*/
    lange.change(function() {
        tableResult.html("");
        wordsHeader.hide();
        setHeight(header_line,  offset, main,  footer, offsetMain,container);
    });
    
    function RemoveSelection(){
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
        else if (document.selection && document.selection.clear) {
            document.selection.clear();
        };
    };
});

/*--------------------------------------------------------------------------------------------------------------*/
/*GET CURRENTLY USED WORDS*/
function get_used_words(text){
    var myRe = /[^>]*>\s*(.*)<br>\s*<\/div>([^<]*)/ig; //expression to get word from <div ....> word <br></div>\n
    text = text.replace(myRe, "$1\n"); //string of used words, delimiter - new line 
    
    return text;
}

/*MAKE TABLE WITH RESULTS*/
function make_table(res){
    var table = "";
    var arr_word = "";
    var words_in_row = 3;
    res = $.trim(res);
    arr_word = res.split("\n");
    table += "<table id=\"print_table\">";
    for(var i = 0; i < arr_word.length; i++){
        if(i %  words_in_row == 0){
            table += "\n<tr>\n";
        }
        //table += "<td>\n<div class=\"print_cell\" id=\"td" + i + "\">" + arr_word[i] + "<br></div></td>\n";
        table += "<td>\n<div class=\"print_cell\" id=\"td" + i + "\">" + arr_word[i] + "</div>\n</td>\n";
        
        if(((i + 1) % words_in_row == 0)||(arr_word.length == (i + 1))){
            table += "\n</tr>\n";
        }
    }
    table += "</table>";
    
    return table;
}